﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using BLL.Entities.Company;
using BLL.Entities;

namespace HTAProDataImporter.Transport
{
    public class AgentTransport : BaseEntityTransport
    {
        public override string CommandText
        {
            get { return "select * from tblAgent"; }
        }
        
        public override void InstanceFromReader(OleDbDataReader DR)
        {
            CompanyAgent agent = CompanyAgent.CreateNewInstance<CompanyAgent>();

            string[] name_parts = DR["Name"].ToString().Trim().Split(' ');

            if (name_parts.Length > 0)
            {
                for (int i = 0; i < name_parts.Length-1; i++ )
                    agent.Person.FirstName += name_parts[i];

                agent.Person.LastName = name_parts[name_parts.Length-1];
            }
            else
            {
                Errors.Add(string.Format("Failed to parse Agent Name '{0}' for  AgentID {1}", DR["Name"], DR["pkAgentID"]));
                return;
            }

            agent.Contact.PhoneWork = DR["Phone"].ToString();
            agent.Contact.PhoneMobile = DR["Cel"].ToString();
            agent.Contact.Email = DR["OtherEmail"].ToString();

            try
            {
                CompanyInfo company = DataStore.Companies[DR["fkCompanyID"].ToString()] as CompanyInfo;

                if (company != null)
                {
                    agent.CompanyID = company.EntityID;
                    DataStore.Agents.Add(DR["pkAgentID"].ToString(), agent);
                }
                else
                {
                    Errors.Add(string.Format("Failed to find CompanyID for AgentID {0}", DR["pkAgentID"]));
                    return;
                }
            }
            catch (Exception ex)
            {
                Errors.Add(string.Format("Exception: {0}", ex.Message)); 
            }

            
        }
    }
}
